package mvc.form;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class Struts_xml {
	
	public Struts_xml()
	{
		
	}
	
	public static Map<String,XmlBean> struts_xml(String xmlPath) throws Exception
	{
		Map<String,XmlBean> xmlbeans = null;
		
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(xmlPath));
		Element root = document.getRootElement();
		
		Element actionforms = root.getChild("formbeans");
		List<Element> forms = actionforms.getChildren();
		
		Element mappings = root.getChild("action-mapping");
		List<Element> actions = mappings.getChildren();
		xmlbeans = new HashMap<String,XmlBean>();
		
		for(Element form:forms){
			XmlBean xmlbean = new XmlBean();
			String path = "";
			
			String beanName = form.getAttributeValue("name");
			String formClass = form.getAttributeValue("class");
			xmlbean.setBeanName(beanName);
			xmlbean.setFormClass(formClass);
			
			for(Element action:actions){
				String actioName = action.getAttributeValue("name");
				if (!actioName.equals(beanName))
				{
					continue;
				}

				String actionClass = action.getAttributeValue("class");
				String actionType=action.getAttributeValue("type");
				path=action.getAttributeValue("path");

				xmlbean.setActionClass(actionClass);
				xmlbean.setActionType(actionType);
				xmlbean.setPath(path);
				
				Map<String,String> actionForward = new HashMap<String,String>();
				List<Element> forwords = action.getChildren();
				for(Element forword:forwords)
				{
					String fname = forword.getAttributeValue("name");
					String fvalue = forword.getAttributeValue("value");
					actionForward.put(fname, fvalue);
				}
				xmlbean.setActionForward(actionForward);
				break;
			}
			
			xmlbeans.put(path, xmlbean);
		}
		
		return xmlbeans;
	}
	
	public static void main(String arg[]) throws Exception
	{
		Map<String,XmlBean> xmlbeans = Struts_xml.struts_xml("Web/WEB-INF/struts-config.xml");
		Set<String> keys = xmlbeans.keySet();
		for(Iterator<String> iterator=keys.iterator();iterator.hasNext();)
		{
			String key = iterator.next();
			XmlBean xmlbean = xmlbeans.get(key);
			
			System.out.println(key+":" + xmlbean);
		}
	}
}
